package com.base.system.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

public final class PackageUtil {
    public static Set<String> getClassStr(String packageStr) throws IOException {
        Set<String> classPath = new HashSet<>();
        Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageStr.replace(".", "/"));
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            String protocol = url.getProtocol();
            if (protocol.equals("file")) {
                String packagePath = url.getPath().replaceAll("%20", " ");
                File[] files = new File(packagePath).listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
                    }
                });
                for (File file : files)
                    if (file.getName().endsWith(".class"))
                        classPath.add(getClassPath(packageStr, file));
                    else
                        classPath.addAll(getClassStr(getPackagePath(packageStr, file)));
            }
        }
        return classPath;
    }

    private static String getClassPath(String packageStr, File file) {
        return packageStr + "." + file.getName().replace(".class", "");
    }

    private static String getPackagePath(String packageStr, File file) {
        return packageStr + "." + file.getName();
    }

    private File[] getFiles(String packagePath) {
        return new File(packagePath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class"));
            }
        });
    }
}
